//引入其他类
import Snake from "./Snake";
import Food from "./food";
import ScorePanel from "./scorePanel";

class GameControl {
    //定义三个属性
    snake: Snake;
    food: Food;
    scorePanel: ScorePanel;

    //创建属性存储蛇的移动方向
    direction: string = `{ArrowRight}`||`{Right}`;
    //创建一个属性记录游戏是否结束
    isLive = true;

    constructor() {
        this.snake = new Snake();
        this.food = new Food();
        this.scorePanel = new ScorePanel();
        this.init();
    }

    //游戏初始化方法
    init() {
        //绑定键盘按下时间
        document.addEventListener('keydown', this.keydownHandler.bind(this));
        //调用run方法
        this.run();
    }
    //创建键盘按下的响应函数
    keydownHandler(event: KeyboardEvent) {
        //检查Key的值是否合法

        this.direction = event.key
    }

    //创建蛇移动的方法
    run() {
        //根据this.direction改变蛇的位置
        let X = this.snake.X;
        let Y = this.snake.Y;

        //根据按键方向修改x,y值
        switch (this.direction) {
            case "ArrowUp":
            case "Up":
                Y-=10;
                break;
            case "ArrowDown":
            case "Down":
                Y+=10;
                break;
            case "ArrowLeft":
            case "Left":
                X-=10;
                break;
            case "ArrowRight":
            case "Right":
                X+=10;
                break;
        }
        
        //检查蛇是否吃到食物
        this.checkEat(X,Y)
            
        //修改蛇X,Y的值
        try{
            this.snake.X = X;
            this.snake.Y = Y; 
        }catch(e:any){
            //异常
            alert(e.message);
            this.isLive = false;
        }
        

        //开启定时调用
        this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level-1) *10);
    }
    //定义一个方法检查蛇是否吃到食物
    checkEat(X:number,Y:number){
       if(X === this.food.X && Y === this.food.Y) {
           //食物位置改变
           this.food.change();
           //分数增加
           this.scorePanel.addScore();
           //增加蛇身子长度
           this.snake.addBody();
       }
    }

}

export default GameControl;